package com.kx.center.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;

public class SQLHelper {

	private static Connection ct = null;
	
	private static PreparedStatement ps = null;
	
	private static ResultSet rs = null;
	public static String kxs = "kxs";
	public static String odb = "odb";
	
	//查询
	public static ArrayList executeQuery(String sql ,String []parameters,String conn){
		
//		System.out.println("sql="+sql);
		ArrayList al = new ArrayList();
		try {
			ct = DBUtil.getConnection(conn);
			ps = ct.prepareStatement(sql);
			if(parameters != null && parameters.length>0){
				for(int i=0;i<parameters.length;i++){
					ps.setString(i+1, parameters[i]);
				}
			}
			rs = ps.executeQuery();
			//获取�?ResultSet 对象的列的编号�?类型和属�?
			ResultSetMetaData rsmd=rs.getMetaData();
			//通过rsmd可以得到该结果集有多少列
			int columnNum=rsmd.getColumnCount();
			//循环的从al中取出数据，并封装到ArrayList�?
			while(rs.next()){
				Object []objects=new Object[columnNum];
				for( int i=0;i<objects.length;i++){
					objects[i]=rs.getObject(i+1);
				}
				al.add(objects);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}finally{
			DBUtil.close(rs, ps, ct);
		}
		return al;
	}
	
	//delete update insert 语句的执行方�?
	public static boolean executeUpdate(String sql ,String []parameters ,String conn){
		System.out.println("sql="+sql);
		boolean b = false;
		try {
			ct = DBUtil.getConnection(conn);
			ps = ct.prepareStatement(sql);
			if(parameters != null && parameters.length>0){
				for(int i=0;i<parameters.length;i++){
					ps.setString(i+1, parameters[i]);
				}
			}
			int num = ps.executeUpdate();
			if(num == 1){
				b = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}finally{
			DBUtil.close(rs, ps, ct);
		}
		return b;
	}
	
	//多个sql语句[delete update insert] 要�?虑事�?
	public static boolean executeUpdate2(String []sql,String [][]parameters ,String conn){
		
		System.out.println("sql="+sql);
		
		try {
			ct = DBUtil.getConnection(conn);
			
			ct.setAutoCommit(false);
			
			for(int i=0;i<sql.length;i++){
				if(parameters[i] != null){
					ps = ct.prepareStatement(sql[i]);
					for(int j=0;j<parameters[i].length;j++){
						ps.setString(j+1, parameters[i][j]);
					}
					ps.executeUpdate();
				}
			}
			ct.commit();
			return true;
			
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ct.rollback();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			throw new RuntimeException(e.getMessage());
		}finally{
			DBUtil.close(rs, ps, ct);
		}
	}
	
	
}
